package com.nananer7;

import java.sql.*;
import java.util.ResourceBundle;

/**
 * 数据库连接工具类
 */

public class DBAccess {
    private static String driverClass;
    private static String url;
    private static String username;
    private static String password;

    static {
        //读取属性文件
        ResourceBundle bundle = ResourceBundle.getBundle("jdbc");
        driverClass = bundle.getString("driverClass");
        url = bundle.getString("url");
        username = bundle.getString("username");
        password = bundle.getString("password");
        try {
            Class.forName(driverClass);
        } catch (ClassNotFoundException e) {
            e.printStackTrace();
        }
    }

    //连接
    public static Connection getConnection() throws Exception {
        return DriverManager.getConnection(url, username, password);
    }

    //关闭资源
    public static void closeAll(ResultSet rs, Statement stm, Connection conn) {
        if(rs != null){
            try{
                rs.close();
            }catch(SQLException e){
                e.printStackTrace();//打印出错原因
            }
            rs = null;
        }
        if(stm != null){
            try{
                stm.close();
            }catch(SQLException e){
                e.printStackTrace();
            }
            stm = null;
        }
        if(conn != null){
            try{
                conn.close();
            }catch(SQLException e){
                e.printStackTrace();
            }
            conn = null;
        }
    }

}
